/*
 * Functions.cpp
 *
 *  Created on: 2012/02/08
 *      Author: takedanaoki
 */
#include "Stdafx.h"
#include "NTEngine/Net/Functions.h"

#include <sstream>

namespace NTEngine {
namespace Net {

string urlencode( const string& src ) {
	ostringstream oss;
	for ( int i = 0; i < src.size(); ++i ) {
		char c = src[ i ];
		// RFC3986に基づく
		if (
			( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ) || ( c >= '0' && c <= '9' ) ||
			c == '-' || c == '_' || c == '.' || c == '~'
		) {
			oss << c;
		} else {
			char s[ 4 ];
			::snprintf( s, sizeof( s ), "%%%02x", c & 0xff );
			oss << s;
		}
	}
	return oss.str();
}

string urldecode( const string& src ) {
	ostringstream oss;
    for ( int i = 0; i < src.size(); ++i ) {
        if ( src[ i ] == '%' ) {
			int word;
			::sscanf( src.substr( i + 1, 2 ).c_str(), "%x", &word );
            oss << static_cast< char >( word & 0xff );
            i = i + 2;
        } else {
            oss << src[ i ];
        }
    }
	return oss.str();
}

} // namespace Net
} // namespace NTEngine
